

const arr = global.get("points");
if (!arr || arr.length === 0) return;

// 先筛选出所有OP10的点并按地址排序
const op10Points = arr
    .filter(tag => tag[0] === '__NAME__')
    .map(tag => ({
        tag: tag,
        address: parseInt(tag[1])
    }))
    .sort((a, b) => a.address - b.address);

let startAddress = null;
let currentAddress = null;
let quantity = 0;
let tags = [];

for (let i = 0; i < op10Points.length; i++) {
    const point = op10Points[i];
    
    // 如果是第一个点或地址不连续
    if (startAddress === null || point.address !== currentAddress + 1) {
        // 如果有待发送的读取请求，先发送
        if (startAddress !== null && quantity > 0) {
            msg.payload = {
                value: 0, // 读取时value不重要
                fc: 3,    // 功能码3: 读取保持寄存器
                unitid: 1,
                address: startAddress,
                quantity: quantity
            };
            msg.tags = tags; // 保存所有相关的tag
            node.send(msg);
        }
        
        // 开始新的连续读取序列
        startAddress = point.address;
        currentAddress = point.address;
        quantity = 1;
        tags = [point.tag];
    } else {
        // 地址连续，增加读取数量
        currentAddress = point.address;
        quantity++;
        tags.push(point.tag);
    }
}

// 发送最后一个连续的读取请求
if (startAddress !== null && quantity > 0) {
    msg.payload = {
        value: 0,
        fc: 3,
        unitid: 1,
        address: startAddress,
        quantity: quantity
    };
    msg.tags = tags;
    node.send(msg);
}